import axios from "axios";

import ElementUI from 'element-ui';
import router from "../router"


let server = axios.create({
  baseURL: "/api", //基础地址
  timeout: 1000 * 10,
  withCredentials: true//携带COOKIE请求需要开启
})
//响应拦截器
server.interceptors.response.use(function (config) {

  if (config.data.code === "10022" || config.data.code === "1004") {
    localStorage.clear("yf-token");
    router.push("/login")
  }

  let { data } = config
  if (!data.state && config.config.url !== "/users/getCaptcha") {
    // alert(data.msg)
    console.log(data)
    if (data.msg === "尚未支付") {
      return
    }
    ElementUI.MessageBox.alert(data.msg, "错误", {
      confirmButtonText: "确认",
      type:"error"
    })
    
  }
  return config
})

//请求拦截器
server.interceptors.request.use(function (config) {
  let excludePath = ["/users/getCaptcha", "/users/login", "/users/verifyCaptcha"]//不需要添加token的路径
  if (excludePath.includes(config.url)) {
    return config;
  } else {
    let token = localStorage.getItem("yf-token")
    config.headers.authorization = token
    return config;
  }
})

export default server